/** 
 * @memo 明细报表Ext-summarygrid方法 
 * @author lic
 * @sample 粘贴用
 
				 	var grid = new SummaryGrid({ 
				   		id:'grid',
						title:'',
						key:'${param.id}',
						region:'center',
						border:false,
				    	bodyStyle: 'padding:5px;', 
						height:all_height-50-40,
						width:all_width-10,  
					    trackMouseOver:true,
					    enableHdMenu:false,
					    enableColumnMove: false,
					    enableColumnHide:false,
						stripeRows: true,
						loadMask:{msg:'正在加载数据，请稍候...'},
						currentTime:'200912',
						currentTimeWeiBiao:'200912'
				    });
		 
 */
var SummaryGrid = Ext.extend(Ext.grid.EditorGridPanel,{
	
  /**
   * 初始化属性
   */
	headFlag:true, //第一加载初始化复杂表头
    customercolumn:'_customer_column_',
	bodyStyle:'padding:0px',
	clicksToEdit:1,
	stripeRows:true,
	trackMouseOver:true,
	iconCls:'icon-grid',
	loadMask:{msg:'正在加载数据，请稍候……'},
	cm:null,
	enableColumnMove:false,
	enableHdMenu:false,
	parseHeader:true, //是否第一次加载,第一次加载会自动创建header和reader
	space:[],
	
	/**
   * 初始化方法
   */
	initComponent : function(){
			 Grid.superclass.initComponent.call(this);
			 this.pageSize=this.pageSize||20;
			 this.baseParams=this.baseParams||{};
			 if(typeof(this.sKey)!=undefined)
				 this.key = this.sKey;
			 this.baseParams.key=this.key;
			 this.baseParams.currentTime=this.currentTime;
			 this.baseParams.currentTimeWeiBiao=this.currentTimeWeiBiao;
			 this.tools=this.tools||[];
			 var head=[]; //复杂表头
             var collist; //宾栏
             var columns; //宾栏表头
             var queryConditions; //查询条件
  			//设置查询参数
  			this.baseParams.collist=collist;
  			if(queryConditions == 'null')
  				queryConditions = '';
  			this.baseParams.conditions=queryConditions;
  			this.baseParams.currentTime=this.currentTime;
             //同步请求后台获取宾栏json ext3.0没找到支持同步的ajax，暂时用query
 			jQuery.ajax({
					type: "POST",
					url: getRootPath()+'/tableRowQuery.table',
					async:false,
					gridId:this.id,
					data:{
	    	 			Constant_DataSource_:'dataSource',
	       	 			Constant_TableName_:'t_reportsummary',
	       	 			Constant_PK_:this.key,
	       	 			Is_Ajax_:'true' 		
	   	 	     	},
					success: function(obj){
	   	 	     		 obj = replaceAll(obj,'\r\n','');
		   	 	     	 var result = Ext.util.JSON.decode(obj);
		   	 	     	 Ext.getCmp(this.gridId).baseParams.xmlId = result.XML_ID_;
		   	 	     	 Ext.getCmp(this.gridId).baseParams.isSum = result.IS_SUM_;
		   	 	     	 Ext.getCmp(this.gridId).baseParams.rowlist = result.ROW_LIST_JSON_;
		   	 	     	 Ext.getCmp(this.gridId).baseParams.collist = result.COL_LIST_JSON_;
		   	 	     	 Ext.getCmp(this.gridId).title="<span style='float:left;' id='tab_tit"+this.gridId+"'>"+result.NAME_+"<span > "+Ext.getCmp(this.gridId).currentTime+"</span></span><span style='float:right;margin-right:20px;'><img style='cursor: pointer;' src='"+getRootPath()+"/images/report/icon_table.gif' onclick='blankRecord(\""+this.gridId+"\");' alt='显示|隐藏空行'/><img style='cursor: pointer;margin-left: 20px;' id='tab_tu' src='"+getRootPath()+"/images/report/icon_histogram.gif' onclick='showChart();' alt='显示图形'/><img style='cursor: pointer;margin-left: 20px;' src='"+getRootPath()+"/images/report/icon_excel.gif' onclick=\"exportData(\'"+this.gridId+"\',\'tab_tit"+this.gridId+"\')\" alt='导出Excel'/></span>";
		   	 	     	 Ext.getCmp(this.gridId).store = new Ext.data.ArrayStore({
		   	 	     		autoLoad:true,
		   	 	     		gridId:this.gridId,
		   	 	     		url:getRootPath() + '/summaryReport.report?method=query&decorate=no',
					       	fields:Ext.util.JSON.decode(result.READER_JSON_),
					       	baseParams:Ext.getCmp(this.gridId).baseParams
					     });
		   	 	     	 //设置空行
		   	 	     	 if(result.SPACE_ROW_INDEX_ != "null"){
		   	 	     		 Ext.getCmp(this.gridId).space = result.SPACE_ROW_INDEX_.split(',');
		   	 	     	 }
		   	 	     	 Ext.getCmp(this.gridId).store.on("load",function(a,b){Ext.getCmp(this.gridId).genSpace(this)});
		   	 	     	 Ext.getCmp(this.gridId).colModel = new Ext.grid.ColumnModel(Ext.util.JSON.decode(result.HEAD_));
	   	 	     	}
			}); 
			 if(!isNull(this.isRemoteExport)){
				 	this.tools.push({
				 		id:'save',
				 		qtip:'导出Excel',
				 		handler: function(e, t, p){
				 			p.exportData(p.isRemoteExport);
				 	}});
			 }
			 this.viewConfig= { 
					 columnsText: '显示列', 
					 sortAscText: '升序', 
					 sortDescText: '降序',
					 forceFit:this.isForceFit	
			 };
			 if(this.isCheck&&isNull(this.singleSelect))
			 {
				 this.singleSelect = false;
			 }
			 if(this.isCheck&&isNull(this.checkOnly))
			 {
				 this.checkOnly = false;
			 }
			 this.selModel=this.isCheck?new Ext.grid.CheckboxSelectionModel({gridId:this.id,singleSelect:this.singleSelect,checkOnly:this.checkOnly}):null;
			 if(!isNull(this.checkId)){ //多选自动保存编号,需要配置checkId
				 this.selModel.on("rowselect",function(o,index,record){ //保存选中行,翻页保存用
					 var grid = Ext.getCmp(o.gridId);
					 var flag = false;
					 for(var i = 0;i<grid.checkedRecord.length;i++){
						 if(grid.checkedRecord[i][grid.checkId] == record.data[grid.checkId]){
							 flag = true;
							 break;
						 }
					 }
					 if(!flag){
						 grid.checkedRecord.push(record.data);
					 }
				 });
				 this.selModel.on("rowdeselect",function(o,index,record){ //删除选中行,翻页保存用
					 var grid = Ext.getCmp(o.gridId);
					 for(var i = 0;i<grid.checkedRecord.length;i++){
						 if(grid.checkedRecord[i][grid.checkId] == record.data[grid.checkId]){
							 grid.checkedRecord.splice(i,1);
							 return;
						 }
					 }
					 
				 });
			 }
			 if(isNull(this.height)){
			 		this.autoHeight=true;
			 }
			 this.isPage = false;
			 if(this.isPage){
			 	//var Message='{1} 条记录/页  当前第 {0} 页   共 {2} 条 ';
				var Message='显示 {0} - {1} 条记录,共 {2}条';
				 if(this.showShort==true){
			 		Message='';
			 	}
			 	 this.bbar=new Ext.PagingToolbar({
			 		 	height:30, 
					 	afterPageText: '/ {0}',
					 	beforePageText: '页',
					 	firstText: '第一页',
					 	prevText: '前一页',
					 	nextText: '后一页',
					 	lastText: '最后一页',
					 	refreshText: '刷新',
					 	store: this.store, 
					 	pageSize: this.pageSize,
					 	displayInfo: true, 
					 	displayMsg: Message, 
					 	emptyMsg: "没有数据" 
				 });
				 if(this.bbar){
		            this.elements += ',bbar';
		            if(typeof this.bbar == 'object'){
		                this.bottomToolbar = this.bbar;
		            }
		            delete this.bbar;
	          }
	       }
			 this.colModel.defaultSortable = false;
			 //this.selModel=new Ext.grid.RowSelectionModel();
			 this.checkedRecord=this.checkedRecord||[];
			 //添加表头编辑
			 this.addListener('headercontextmenu', rightClickFn);
			 this.addListener('headerdblclick', headerDbclickFn);
			 this.addListener('headerclick', headerClickFn);
 			//复杂表头配置
 			this.plugins = [new Ext.ux.plugins.GroupHeaderGrid({rows:[],columns:[]})];
	},

  /**
   * 方法
   */	
	setKey:function(key){
		this.ds.baseParams.key = key;
		this.parseHeader = true; //需要重新配置header
	},
	getKey:function(){
		return this.ds.baseParams.key;
	},
	setCallBack:function(callback){
		this.ds.callback = callback;
		this.parseHeader = true; //需要重新配置header
	},
	load:function(){
		this.ds.load({params:{start:0,limit:this.pageSize}});
	},
	reload:function(){
		this.store.load();
	},
	getParam:function(p){
		return this.ds.baseParams[p];
	},
	setParam:function(p,v){
		this.ds.baseParams[p]=v;
	},
	setParams:function(j){
		for(var p in j){
			this.setParam(p,j[p]);
		}
	},
	getHead:function(){
		return this.ds.head;
	},
	exportData:function(flag){
		if(flag){
			var url = getRootPath()+"/extExportExcel.report?decorate=no&key="+this.ds.baseParams.key+"&filename="+encodeURI(this.title);
			for(var p in this.ds.baseParams){
				url+="&"+p+"="+this.ds.baseParams[p];
			}
			url+="&isExcelRank="+this.isExcelRank;
			if(this.isCommonAdapter)
			{
				var start = 0,limit = this.ds.getTotalCount();
				url += "&adapter_id_="+this.adapter_id_+"&start="+start+"&limit="+limit;
			}
			window.location.href=url;
		}
		else{
			exportData(this.id,this.title);
		}
	},
	getTree:function(){
		var j1 = this.ds.head;
		var j2 = "[{}";
		for(var p=0;p<j1.length;p++)
		{
			if(j1[p].dataIndex.indexOf(this.customercolumn)==-1)
				j2+=",{'text':'"+j1[p].header+"',expanded: false,leaf:true}";
		};
		j2+="]";
		j2=eval(j2.replace("{},",""));
		return j2;
	},
	getSelectionsByCheckId:function(){
		var result='';
		for(var i=0;i<this.checkedRecord.length;i++){
			result += "'"+this.checkedRecord[i][this.checkId]+"'";
			if(i+1<this.checkedRecord.length)
				result += ',';
		}
		return result;
	},
	getSelections:function(target){
		var rows = this.getSelectionModel().getSelections();
		if(rows=='')return null;
		var result='';
		for(var i=0;i<rows.length;i++){
			result += rows[i].get(target);
			if(i+1<rows.length)
				result += ',';
		}
		return result;
	},
	genSpace:function(ds){
		for(var i = 0;i < this.space.length;i++){
			ds.insert(parseInt(this.space[i]), new Ext.data.Record());
		}
		ds.commitChanges();
	}
});

Ext.reg('xgrid', Grid);
//非空判断
function isNull(o){
	return (typeof(o) == 'undefined' || o == null);
}